package com.lumlord.util;

import com.google.gson.JsonObject;
import com.lumlord.common.base.ApiController;
import com.lumlord.common.exception.BusinessException;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

/**
 * 签名加密认证
 * @author gpf
 *
 */
public class SignTool extends ApiController {

    private String json;
    private JsonObject jsonObject;
    private List<String> list = new ArrayList<String>();
    /** 签名信息**/
    public static final String SIGN_NAME = "_sign";
    /** 时间戳信息**/
    public static final String TIME_STAMP = "_timeStamp";
    /***
     * 客户端签名信息
     */
    private String clientSign;



    /**
     * sign md5
     */
    private String signMd5;
    /**
     * 时间戳
     */
    private Long timeStamp ;
    /**
     * 递归读取所有的key
     *
     * @param jsonObject
     */
    private  void getAllKey(JSONObject jsonObject) {

        Iterator<String> keys = jsonObject.keySet().iterator();// jsonObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();

            if (jsonObject.get(key) instanceof JSONObject) {
                JSONObject innerObject = (JSONObject) jsonObject.get(key);
               getAllKey(innerObject);
            } else if (jsonObject.get(key) instanceof JSONArray) {
                JSONArray innerObject = (JSONArray) jsonObject.get(key);
                getAllKey(innerObject);
            }else{
                list.add(key+"="+jsonObject.get(key));
            }
        }

    }

    private  void getAllKey(JSONArray json1) {

        if (json1 != null ) {
            Iterator i1 = json1.iterator();
            while (i1.hasNext()) {
                Object key = i1.next();
                if (key instanceof  JSONObject) {
                    JSONObject innerObject = (JSONObject) key;
                    getAllKey(innerObject);
                } else if (key instanceof JSONArray) {
                    JSONArray innerObject = (JSONArray) key;
                    getAllKey(innerObject);
                }else{
                    list.add(key+"");
                }
            }
        }

    }
    /** 移除标记 和 timestamp **/
    private void removeSignTimeStamp(  JSONObject jsonObject ) throws  BusinessException {
        this.clientSign = jsonObject.getString(SIGN_NAME);
        //sign = true 通過
        if(this.clientSign.equals("true")){
            return;
        }

        this.timeStamp = jsonObject.getLong(TIME_STAMP);

        jsonObject.remove(SIGN_NAME);
        jsonObject.remove(TIME_STAMP);
    }

    public String buildSign(String url ,String json) throws  BusinessException {
        JSONObject jsonObject = new JSONObject(json);
        //移除 sign timestamp
       removeSignTimeStamp(jsonObject);
       //递归key 值
       getAllKey(jsonObject);
       String args[] =  new String[list.size()];
       Arrays.sort(list.toArray(args));

       StringBuilder stringBuffer = new StringBuilder(url+"?");
       for(String key:args){
            stringBuffer.append(key+"&");
       }

       stringBuffer.append(TIME_STAMP+"="+this.timeStamp);
       setSignMd5(stringBuffer.toString());
       return stringBuffer.toString();
    }

    public String getSignMd5() {
        return signMd5;
    }

    public void setSignMd5(String signMd5) {
        this.signMd5 = signMd5;
    }
    public Long getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(Long timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getClientSign() {
        return clientSign;
    }

    public void setClientSign(String clientSign) {
        this.clientSign = clientSign;
    }

    public static void main(String[] args) throws BusinessException {

        String json = ("  {\n" +
                "    \"error_code\": 0,\n" +
                "    \"data\": {\n" +
                "      \"uid\": \"1\",\n" +
                "      \"username\": \"12154545\",\n" +
                "      \"name\": \"吴系挂\",\n" +
                "      \"groupid\": 2 ,\n" +
                "      \"reg_time\": \"1436864169\",\n" +
                "      \"last_login_time\": \"0\",\n" +
                "    },\n" +
                "    \"arry\":[\n" +
                "        {\"test11\":1,\"test2\":\"test2\"},\n" +
                "        {\"test11\":1,\"test2\":\"test3\"}\n" +
                "    ],\n" +
                "    \"ints\":[1,2,3],\n" +
                "    \"_timeStamp\":1572583648046,\n" +
                "    \"_sign\":\"AF926723406181671F130588A1A2C6FB\"\n" +
                "  }");
      //  json = "{\"sign\":\"10DC6D75EB7482FA41F4D61076E0DC32\",\"timeStamp\":1572583648046}";
        SignTool signTool = new SignTool();
        System.out.println(json);
        System.out.println(System.currentTimeMillis());
        String md5Val =  signTool.buildSign("lumlord_core/api/custom/v1/user/login",json);
        System.out.println(md5Val);
        System.out.println(MD5Util.encode(md5Val).toUpperCase());    }
}
